package com.recipedb.sprint.security;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;

@Component
public class JwtUtil {

    private static final String FIXED_TOKEN = "fixed-test-token-12345";
    private static final String FIXED_USERNAME = "root";
    private static final boolean USE_FIXED_TOKEN = false;

    // 使用明确的字符集
    private static final Key key = Keys.hmacShaKeyFor("your-32+chars-secret-key-goes-here!".getBytes(StandardCharsets.UTF_8));
    private static final long EXPIRATION_TIME = 1000L * 60 * 60 * 24;

    public static String generateToken(String username) {
        System.out.println(" [JWT生成] 用户名: " + username + ", USE_FIXED_TOKEN: " + USE_FIXED_TOKEN);

        if (USE_FIXED_TOKEN) {
            System.out.println(" [JWT生成] 返回固定Token: " + FIXED_TOKEN);
            return FIXED_TOKEN;
        }

        String token = Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(key, SignatureAlgorithm.HS256) // 明确指定算法
                .compact();

        System.out.println(" [JWT生成] 成功生成Token，长度: " + token.length());
        System.out.println(" [JWT生成] Token内容: " + token);
        return token;
    }

    public static String validateToken(String token) {
        System.out.println(" [JWT验证] 开始验证Token，USE_FIXED_TOKEN: " + USE_FIXED_TOKEN);
        System.out.println(" [JWT验证] 输入Token: " + token);

        if (USE_FIXED_TOKEN) {
            boolean isValid = FIXED_TOKEN.equals(token);
            System.out.println(" [JWT验证] 固定Token验证结果: " + (isValid ? "成功" : "失败"));
            return isValid ? FIXED_USERNAME : null;
        }

        if (token == null || token.trim().isEmpty()) {
            System.out.println(" [JWT验证] Token为空");
            return null;
        }

        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();

            String username = claims.getSubject();
            Date expiration = claims.getExpiration();

            System.out.println(" [JWT验证] Token验证成功");
            System.out.println(" [JWT验证] 用户名: " + username);
            System.out.println(" [JWT验证] 过期时间: " + expiration);
            System.out.println(" [JWT验证] 当前时间: " + new Date());
            System.out.println(" [JWT验证] 是否已过期: " + expiration.before(new Date()));

            return username;

        } catch (ExpiredJwtException e) {
            System.out.println(" [JWT验证] Token已过期: " + e.getMessage());
            return null;
        } catch (MalformedJwtException e) {
            System.out.println(" [JWT验证] Token格式错误: " + e.getMessage());
            System.out.println(" [JWT验证] 可能原因: Token被篡改或格式不正确");
            return null;
        } catch (SignatureException e) {
            System.out.println(" [JWT验证] Token签名验证失败: " + e.getMessage());
            System.out.println(" [JWT验证] 可能原因: 密钥不匹配或Token被篡改");
            return null;
        } catch (UnsupportedJwtException e) {
            System.out.println(" [JWT验证] 不支持的JWT格式: " + e.getMessage());
            return null;
        } catch (IllegalArgumentException e) {
            System.out.println(" [JWT验证] Token参数错误: " + e.getMessage());
            return null;
        } catch (JwtException e) {
            System.out.println(" [JWT验证] Token验证异常: " + e.getClass().getSimpleName() + " - " + e.getMessage());
            return null;
        }
    }
}